<?php

namespace addons\cms\model;

use app\common\model\User;
use think\Model;

/**
 * 会员积分日志模型
 */
class ScoreLog extends Model
{

    // 表名
    protected $name = 'user_score_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
    ];

    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public static function saveLog($type, $user_id,$param_id, $remark = '')
    {
        $config = get_addon_config('cms');
        if (in_array($type, array_keys($config['score']))){
            $score = $config['score'][$type];
        }else{
            return 0;
        }
        if ($score == 0){
            return 0;
        }
        $score_limit = $config['score_limit'][$type] ?? 0;
        $count = \app\common\model\ScoreLog::where(['user_id' => $user_id, 'type' => $type,'param_id' => $param_id])
            ->whereTime('createtime','today')
            ->count();

        if ($count != 0){
            return 0;
        }

        if ($score_limit != 0){
            $limit_count =  \app\common\model\ScoreLog::where(['user_id' => $user_id, 'type' => $type])
                ->whereTime('createtime','today')
                ->count();
            if ($limit_count >= $score_limit){
                return 0;
            }
        }
        $remark = $config['score_remark'][$type] ?? $remark;
        //增加消息日志
        $content = '';
        switch ($type){
            case 'postcomment':
                $content = "[积分奖励]每日发布评论,获得积分奖励：{$score}";
                break;
            case 'activity':
                $activity_title = Activity::where('id', $param_id)->value('title');
                $content = "[报名成功]参加‘{$activity_title}’获得成功，获得积分奖励：{$score}";
                break;
            case 'praise':
                $content = "[积分奖励]每日点赞资讯/活动，获得积分奖励：{$score}";
                break;
            case 'collection':
                $content = "[积分奖励]每日收藏资讯/活动，获得积分奖励：{$score}";
                break;
            case 'post_browse':
                $content = "[积分奖励]每日阅读资讯/活动，获得积分奖励：{$score}";
                break;
            case 'societies':
                $content = "[入会成功]提交加入社团，获得积分奖励：{$score}";
                break;
        }

        Notice::create([
            'type' => $type,
            'title' => '系统消息',
            'user_id' => $user_id,
            'content' => $content,
            'createtime' => time()
        ]);
        User::score($score,$type, $user_id, $param_id,$remark);
        return $score;
    }


    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}
